package com.roads.agency.service.impl;

import com.roads.common.constant.Constants;
import com.roads.common.constant.UserConstants;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProInstitution;
import com.roads.project.domain.ProAgencyBoq;
import com.roads.project.mapper.ProInstitutionMapper;
import com.roads.project.mapper.ProAgencyBoqMapper;
import com.roads.agency.domain.AgencyBoq;
import com.roads.agency.mapper.AgencyBoqMapper;
import com.roads.agency.service.IAgencyBoqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 代建清单Service业务层处理
 * 
 * @author nhp
 * @date 2023-08-09
 */
@Service
public class AgencyBoqServiceImpl implements IAgencyBoqService {

    @Autowired
    private AgencyBoqMapper mapper;

    @Autowired
    private ProInstitutionMapper institutionMapper;

    @Autowired
    private ProAgencyBoqMapper proAgencyBoqMapper;

    /**
     * 根据主键ID查询详情
     * 
     * @param id 代建清单主键
     * @return 代建清单
     */
    @Override
    public AgencyBoq getModelById(Integer id) {
        return mapper.getModelById(id);
    }

    /**
     * 根据标段清单编号查询详情
     *
     * @param institutionBoqCode 标段编号
     * @return 代建清单
     */
    @Override
    public AgencyBoq getModelByInstitutionBoqCode(String institutionBoqCode) {
        return mapper.getModelByInstitutionBoqCode(institutionBoqCode);
    }

    /**
     * 查询列表
     * 
     * @param model 代建清单
     * @return 代建清单
     */
    @Override
    public List<AgencyBoq> selectModelList(AgencyBoq model) {
        return mapper.selectModelList(model);
    }

    /**
     * 查询列表 --主要用于代建计量添加，在同一期不能重复添加，并且都为叶子节点
     *
     * @param model 查询条件
     * @return 结果
     */
    @Override
    public List<AgencyBoq> selectBoqListByMeterage(AgencyBoq model) {
        return mapper.selectBoqListByMeterage(model);
    }

    /**
     * 查询清单树形列表(名称=清单编号+清单名称)
     *
     * @param boq 清单
     * @return 清单集合
     */
    @Override
    public List<AgencyBoq> selectTreeList(AgencyBoq boq) {
        return mapper.selectTreeList(boq);
    }

    /**
     * 根据清单编号查询子节点
     *
     * @param institutionCode 标段编号
     * @param templateCode 模板编号
     * @param boqType 清单类型
     * @param boqCode 清单编号
     * @return 清单集合
     */
    @Override
    public List<AgencyBoq> selectChildrenList(String institutionCode, String templateCode, String boqType, String boqCode) {
        return mapper.selectChildrenList(institutionCode, templateCode, boqType, boqCode);
    }

    /**
     * 校验清单编号是否唯一
     *
     * @param boq 清单实体
     * @return 结果
     */
    @Override
    public String checkBoqCodeUnique(AgencyBoq boq) {
        Integer id = StringUtils.isNull(boq.getId()) ? -1 : boq.getId();
        AgencyBoq search = mapper.getModelByCode(boq.getInstitutionCode(), boq.getTemplateCode(), boq.getBoqType(), boq.getBoqCode());
        if (StringUtils.isNotNull(search) && !search.getId().equals(id)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 同步
     *
     * @param model 代建清单
     * @return 结果
     */
    @Override
    public int sync(AgencyBoq model) {
        // 先删除清单
        mapper.deleteByModel(model);
        ProInstitution institution = institutionMapper.getModelByInnerCode(model.getInstitutionCode());
        // 查询项目级代建清单
        ProAgencyBoq search = new ProAgencyBoq();
        search.setProjectId(institution.getProjectId());
        List<ProAgencyBoq> boqList = proAgencyBoqMapper.selectModelList(search);
        if (StringUtils.isNotNull(boqList) && boqList.size() > 0) {
            List<AgencyBoq> insertList = new ArrayList<>();
            Date nowDate = DateUtils.getNowDate();
            for (ProAgencyBoq boq : boqList) {
                AgencyBoq insert = new AgencyBoq();
                insert.setInstitutionCode(model.getInstitutionCode());
                insert.setTemplateCode(model.getTemplateCode());
                insert.setBoqType(model.getBoqType());
                String boqCode = boq.getBoqCode();
                // 标段清单 = 标段编号+"-"+模板编号+"-"+清单类型+"-"+清单编码
                String institutionBoqCode = model.getInstitutionCode() + Constants.BOQ_SEPARATOR
                        + model.getTemplateCode() + Constants.BOQ_SEPARATOR
                        + model.getBoqType() + Constants.BOQ_SEPARATOR + boqCode;
                insert.setInstitutionBoqCode(institutionBoqCode);
                insert.setBoqCode(boqCode);
                insert.setBoqName(boq.getBoqName());
                insert.setParentCode(boq.getParentCode());
                insert.setAncestors(boq.getAncestors());
                insert.setOrderNum(boq.getOrderNum());
                insert.setLevel(boq.getLevel());
                insert.setLeafNode(boq.getLeafNode());
                insert.setUnit(boq.getUnit());
                insert.setCreateBy(SecurityUtils.getUsername());
                insert.setCreateTime(nowDate);
                insertList.add(insert);
            }
            // 批量新增
            mapper.insertBatch(insertList);
        }
        return 1;
    }

    /**
     * 新增
     * 
     * @param model 代建清单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(AgencyBoq model) {
        model.setCreateTime(DateUtils.getNowDate());
        // 父项编号
        String parentCode = model.getParentCode();
        // 如果是根节点
        if (StringUtils.isEmpty(parentCode)) {
            model.setLevel(1);
            model.setAncestors(model.getBoqCode());
        } else {
            // 查询父清单
            AgencyBoq parentBoq = mapper.getModelByCode(model.getInstitutionCode(), model.getTemplateCode(), model.getBoqType(), parentCode);
            // 是否更新父清单
            if (Constants.YES.equals(parentBoq.getLeafNode())) {
                parentBoq.setLeafNode(Constants.NO);
                mapper.update(parentBoq);
            }
            model.setLevel(parentBoq.getLevel() + 1);
            model.setAncestors(parentBoq.getAncestors() + "," + model.getBoqCode());
        }
        // 标段清单 = 标段编号+"-"+模板编号+"-"+清单类型+"-"+清单编码
        String institutionBoqCode = model.getInstitutionCode() + Constants.BOQ_SEPARATOR
                + model.getTemplateCode() + Constants.BOQ_SEPARATOR
                + model.getBoqType() + Constants.BOQ_SEPARATOR + model.getBoqCode();
        // 设置总数量和剩余数量
        BigDecimal periodAmount = model.getPeriodAmount() == null ? BigDecimal.valueOf(0) : model.getPeriodAmount();
        model.setAmount(periodAmount);
        model.setRemainderAmount(periodAmount);
        model.setAlreadyAmount(BigDecimal.valueOf(0));
        model.setInstitutionBoqCode(institutionBoqCode);
        model.setLeafNode(Constants.YES);
        mapper.insert(model);
        return 1;
    }

    /**
     * 修改
     * 
     * @param model 代建清单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(AgencyBoq model) {
        // 取出原有清单
        AgencyBoq oldBoq = mapper.getModelById(model.getId());
        int oldLevel = oldBoq.getLevel();
        // 新父项清单处理
        int oldParentLevel = 0;
        String nowAncestors = "";
        String oldAncestors = oldBoq.getAncestors();
        String oldParentCode = StringUtils.isEmpty(oldBoq.getParentCode()) ? "" : oldBoq.getParentCode();
        String nowParentCode = StringUtils.isEmpty(model.getParentCode()) ? "" : model.getParentCode();
        // 如果父项发生变化
        if (!oldParentCode.equals(nowParentCode)) {
            // 原父项清单处理
            if (!StringUtils.isEmpty(oldBoq.getParentCode())) {
                AgencyBoq oldParent = mapper.getModelByCode(oldBoq.getInstitutionCode(), oldBoq.getTemplateCode(), oldBoq.getBoqType(), oldBoq.getParentCode());
                // 父项清单下是否有子节点
                int countOldChildren = mapper.countChildren(oldBoq.getInstitutionCode(), oldBoq.getTemplateCode(), oldBoq.getBoqType(), oldParent.getBoqCode());
                if (countOldChildren == 1) {
                    oldParent.setLeafNode(Constants.YES);
                    mapper.update(oldParent);
                }
            }

            if (!StringUtils.isEmpty(model.getParentCode())) {
                AgencyBoq nowParent = mapper.getModelByCode(oldBoq.getInstitutionCode(), oldBoq.getTemplateCode(), oldBoq.getBoqType(), model.getParentCode());
                oldParentLevel = nowParent.getLevel();
                if (Constants.YES.equals(nowParent.getLeafNode())) {
                    nowParent.setLeafNode(Constants.NO);
                    mapper.update(nowParent);
                }
            }
        }

        // 计算级别差
        int level = oldParentLevel + 1;
        int dValue = level - oldLevel;
        if (oldParentCode.equals(nowParentCode)) {
            level = model.getLevel();
            dValue = 0;
        }
        // 计算内码
        if (StringUtils.isEmpty(model.getParentCode())) {
            nowAncestors = model.getBoqCode();
        } else {
            AgencyBoq nowParent = mapper.getModelByCode(oldBoq.getInstitutionCode(), oldBoq.getTemplateCode(), oldBoq.getBoqType(), model.getParentCode());
            nowAncestors = nowParent.getAncestors() + "," + model.getBoqCode();
        }
        // 查询子清单
        List<AgencyBoq> childrenList = mapper.selectChildrenList(oldBoq.getInstitutionCode(), oldBoq.getTemplateCode(), oldBoq.getBoqType(), oldBoq.getBoqCode());
        if (childrenList.size() > 0) {
            for (AgencyBoq children : childrenList) {
                // 设置子节点的级别
                children.setLevel(children.getLevel() + dValue);
                children.setAncestors(children.getAncestors().replace(oldAncestors, nowAncestors));
                if (!model.getBoqCode().equals(oldBoq.getBoqCode())) {
                    if (children.getParentCode().equals(oldBoq.getBoqCode())) {
                        children.setParentCode(model.getBoqCode());
                    }
                }
            }
            mapper.updateBatch(childrenList);
        }
        // 设置清单
        model.setAncestors(nowAncestors);
        model.setLevel(level);
        // 标段清单 = 标段编号+"-"+模板编号+"-"+清单类型+"-"+清单编码
        String institutionBoqCode = model.getInstitutionCode() + Constants.BOQ_SEPARATOR
                + model.getTemplateCode() + Constants.BOQ_SEPARATOR
                + model.getBoqType() + Constants.BOQ_SEPARATOR + model.getBoqCode();
        model.setInstitutionBoqCode(institutionBoqCode);
        // 设置总数量和剩余数量
        BigDecimal periodAmount = model.getPeriodAmount() == null ? BigDecimal.valueOf(0) : model.getPeriodAmount();
        model.setAmount(periodAmount);
        model.setRemainderAmount(periodAmount);
        model.setAlreadyAmount(BigDecimal.valueOf(0));
        model.setUpdateTime(DateUtils.getNowDate());
        mapper.update(model);
        return 1;
    }

    /**
     * 批量删除
     * 
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    public int deleteByIds(Integer[] ids) {
        return mapper.deleteByIds(ids);
    }

    /**
     * 删除
     * 
     * @param id 代建清单主键
     * @return 结果
     */
    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }
}
